package main;

import java.util.Enumeration;

import gameHandling.BasicHandling;
import gameHandling.PlaceFenceHandling;
import gameHandling.PlaceHeroHandling;
import gameHandling.RushHanding;
import gameObject.Fence;
import gameObject.Hero;
import gameObject.item.ItemArm;
import gameObject.item.ItemEquipment;
import gameObject.item.ItemSuit;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;

import control.ControlCommand;
import control.DrawButton;
import control.HeroDisplayPanel;
import control.IconBox;
import control.ListBox;
import control.Panel;
import control.TabControl;
import control.TextControl;

public class PlayingCanvas extends GameCanvas implements Runnable {
	private static PlayingCanvas instance;
	private ItemEquipment[] tempItem = new ItemEquipment[18];
	protected boolean lockScreen;
	protected MainMidlet midlet;
	protected boolean isInterrupting;
	protected boolean isPlaying;
	protected GameManager game;
	protected Panel mainBar;
	protected HeroDisplayPanel heroPanel;
	public TabControl toolTab;
	protected TextControl levelText;
	protected TextControl lifeText;
	protected TextControl moneyText;
	protected TextControl itemInfoText;
	protected TextControl hireHeroText;
	protected ListBox storeListBox;
	protected ListBox inventoryListBox;
	protected DrawButton sellButton;
	protected DrawButton buyButton;
	protected DrawButton equipButton;
	protected DrawButton inventoryButton;
	protected DrawButton storeButton;
	protected TabControl itemBoxTab;
	protected TabControl heroTabControl;

	protected String message;
	protected int messageY;

	public DrawButton btnPutFence;

	protected Tutorial tutorial;

	public static void init(MainMidlet midlet) {
		instance = new PlayingCanvas(midlet);
	}

	public static PlayingCanvas getInstance() {
		return instance;
	}

	public static GameManager getGame() {
		return instance.game;
	}

	private PlayingCanvas(MainMidlet midlet) {
		super(true);
		this.midlet = midlet;
		setFullScreenMode(true);

		game = new GameManager();
		lockScreen = false;
		initControl();
		message = "";
		messageY = -1;
	}

	public void resetGame() {
		game = new GameManager();
		lockScreen = false;
		message = "";
		messageY = -1;
		toolTab.setTab(0);
		tutorial = null;
	}
	public void setTutorial() {
		game = new GameManager();
		game.money = 200;
		lockScreen = false;
		message = "";
		messageY = -1;
		toolTab.setTab(0);
		tutorial = new Tutorial(midlet);
	}
	public boolean isPlaying(){
		return !isInterrupting;
	}
	public void run() {
		Graphics g = getGraphics();
		long startTime, endTime, delay;
		while (isPlaying) {
			if (isInterrupting)
				continue;

			startTime = System.currentTimeMillis();
			update();
			display(g);
			endTime = System.currentTimeMillis();

			try {
				delay = 80 - (endTime - startTime);
				if (delay > 0) {
					Thread.sleep(delay);
				}
			} catch (InterruptedException ex) {
			}
		}
	}

	private void update() {
		game.update();
		levelText.setText("Level " + String.valueOf(game.level + 1));
		lifeText.setText("$(1)" + String.valueOf(game.numLife));
		moneyText.setText("$(0)" + String.valueOf(game.money));
	}

	private void display(Graphics g) {

		g.setColor(0xFF00FF00);
		game.paint(g);
		mainBar.paint(g);

		if(tutorial != null){
			tutorial.paint(g);
		}
		if (messageY > 0) {
			messageY -= 5;
			g.setColor(0x10FFFFFF);
			g.drawString(message, 5, messageY, Graphics.LEFT | Graphics.TOP);
			if (messageY < 250) {
				messageY = -1;
			}
		}
		flushGraphics();
	}

	public void setMessage(String str) {
		message = str;
		messageY = 340;
	}

	public void start() {
		Thread t = new Thread(this);
		t.start();
		isInterrupting = false;
		isPlaying = true;
	}

	public void stop() {
		isInterrupting = true;
		isPlaying = false;
	}

	/*
	 * public void pause() { isInterrupting = true; //isPlaying = false; }
	 * public void resume() { isInterrupting = false; //isPlaying = false; }
	 */

	protected void pointerPressed(int x, int y) {
		if (tutorial != null && !tutorial.pointerPressed(x, y)) {
			return;
		}
		if (!lockScreen) {
			game.pointerPressed(x, y);
		}
		mainBar.pointerPressed(x, y);
	}

	protected void pointerReleased(int x, int y) {
		
		if (tutorial != null && !tutorial.pointerReleased(x, y)) {
			System.out.println("----------");
			System.out.println(tutorial);
			System.out.println("^^^^^^^^^^^^");
			return;
		}
		if (!lockScreen) {
			game.pointerReleased(x, y);
		}
		mainBar.pointerReleased(x, y);
	}

	protected void pointerDragged(int x, int y) {
		if (tutorial != null && !tutorial.pointerDragged(x, y)) {
			return;
		}
		if (!lockScreen) {
			game.pointerDragged(x, y);
		}
		mainBar.pointerPressed(x, y);
	}

	// ///////////// ***********************************************

	public void doneHandling() {
		lockScreen = false;
		toolTab.setTab(0);
		game.extendHandling = new BasicHandling();
	}

	public void forcusHero(Hero hero) {
		game.forcusHero = hero;
		toolTab.setTab(4);
		heroTabControl.setVisible(false);
		heroPanel.setHeroInfo(hero);
	}

	public void initControl() {
		int buttonH = 40;
		int buttonW = 50;

		// / ************* MAIN TAB

		final Panel mainTab = new Panel(0, 360, 240, buttonH, 4);
		mainTab.setControl(0, new DrawButton(1, 0, 360, buttonW, buttonH));// BUTTON
																			// NEW
																			// HERO
		mainTab.get(0).setCommand(new ControlCommand() {
			public void Do() {
				if(game.listHero.size() == 8){
					setMessage("No more hero to hire");
					return;
				}
				hireHeroText.setText("Hire more hero\n"+game.getHeroCost()+"$(0)");
				toolTab.setTab(1);
				game.extendHandling = new PlaceHeroHandling();
			}
		});
		mainTab.setControl(1, new DrawButton(2, 50, 360, buttonW, buttonH));// BUTTON
																			// BLOCK
		mainTab.get(1).setCommand(new ControlCommand() {
			public void Do() {
				toolTab.setTab(2);
				game.extendHandling = new PlaceFenceHandling();
			}
		});
		mainTab.setControl(2, new DrawButton(3, 100, 360, buttonW, buttonH));// BUTTON
																				// ITEM
		mainTab.get(2).setCommand(new ControlCommand() {
			public void Do() {
				lockScreen = true;
				toggleIventory();
				toolTab.setTab(3);
			}
		});
		mainTab.setControl(3, new DrawButton(6, 190, 360, buttonW, buttonH)); // BUTTON
																				// START
		mainTab.get(3).setCommand(new ControlCommand() {
			public void Do() {
				// START
				game.extendHandling = new RushHanding(game.level);
				toolTab.setTab(5);
			}
		});
		hireHeroText = new TextControl("Hire more hero\n0$(0)", 50, 365);
		final Panel newHeroTab = new Panel(0, 360, 240, buttonH, 3);
		newHeroTab.setControl(0, new IconBox(1, 0, 360, buttonH, buttonH));
		newHeroTab.setControl(1, hireHeroText);
		newHeroTab.setControl(2, new DrawButton(7, 200, 360, buttonH, buttonH));
		newHeroTab.get(2).setCommand(new ControlCommand() {
			public void Do() {
				doneHandling();
			}
		});

		// / ************* BLOCK TAB

		final Panel blockTab = new Panel(0, 360, 240, buttonH, 4);
		blockTab.setControl(0, new IconBox(2, 0, 360, buttonH, buttonH));
		blockTab.setControl(1,
				new TextControl("Put the fence\n10$(0)", 50, 365));
		btnPutFence = new DrawButton(8, 160, 360, buttonH, buttonH);
		btnPutFence.setVisible(false);
		btnPutFence.setCommand(new ControlCommand() {
			public void Do() {
				game.extendHandling.execute();
				btnPutFence.setVisible(false);
			}
		});
		blockTab.setControl(2, btnPutFence);
		blockTab.setControl(3, new DrawButton(7, 200, 360, buttonH, buttonH));
		blockTab.get(3).setCommand(new ControlCommand() {
			public void Do() {
				doneHandling();
			}
		});

		// / ************* ITEM TAB
		initItemBox();

		final Panel inventoryTab = new Panel(0, 180, 240, 60, 3);
		inventoryTab.setControl(0, itemInfoText);
		inventoryTab.setControl(1, sellButton);
		inventoryTab.setControl(2, inventoryListBox);

		final Panel storeTab = new Panel(0, 180, 240, 60, 3);
		storeTab.setControl(0, itemInfoText);
		storeTab.setControl(1, buyButton);
		storeTab.setControl(2, storeListBox);

		itemBoxTab = new TabControl(2);
		itemBoxTab.setControl(0, inventoryTab);
		itemBoxTab.setControl(1, storeTab);

		inventoryButton = new DrawButton(4, 0, 360, buttonW, buttonH);
		inventoryButton.setCommand(new ControlCommand() {
			public void Do() {
				toggleIventory();
			}
		});
		storeButton = new DrawButton(5, 50, 360, buttonW, buttonH);
		storeButton.setCommand(new ControlCommand() {
			public void Do() {
				toggleStore();
			}
		});
		final Panel itemTab = new Panel(0, 360, 240, buttonH, 4);
		// itemTab.setControl(0, new IconBox(3, 0, 360, buttonH, buttonH));
		itemTab.setControl(0, inventoryButton);
		itemTab.setControl(1, storeButton);
		itemTab.setControl(2, new DrawButton(7, 200, 360, buttonH, buttonH));
		itemTab.get(2).setCommand(new ControlCommand() {
			public void Do() {
				doneHandling();
			}
		});
		itemTab.setControl(3, itemBoxTab);

		// / ************* HERO TAB

		heroPanel = new HeroDisplayPanel(0, 230, 240, 130);
		heroPanel.setCommandArm(new ControlCommand() {
			public void Do() {
				initInventory(ItemEquipment.ARM);
				heroTabControl.setTab(1);
			}
		});
		heroPanel.setCommandSuit(new ControlCommand() {
			public void Do() {
				initInventory(ItemEquipment.SUIT);
				heroTabControl.setTab(1);
			}
		});

		final Panel equipItemTab = new Panel(0, 180, 240, 60, 3);
		equipItemTab.setControl(0, itemInfoText);
		equipItemTab.setControl(1, new DrawButton(8, 200, 200, 40, 40));
		equipItemTab.get(1).setCommand(new ControlCommand() {
			public void Do() {
				if (inventoryListBox.getInfo() != -1) {
					game.removeDrawableObject(game.forcusHero);
					int index = inventoryListBox.getSellectIndex();
					if (tempItem[index].getItemType() == ItemEquipment.ARM) {
						ItemEquipment currentItem = game.forcusHero.getArm();
						if (currentItem != null && currentItem.getId() != 0) {
							game.listItem.addElement(currentItem);
						}
						game.forcusHero.setArm((ItemArm) tempItem[index]);
					}
					if (tempItem[index].getItemType() == ItemEquipment.SUIT) {
						ItemEquipment currentItem = game.forcusHero.getSuit();
						if (currentItem != null) {
							game.listItem.addElement(currentItem);
						}
						game.forcusHero.setSuit((ItemSuit) tempItem[index]);
					}
					game.listItem.removeElement(tempItem[index]);
					heroPanel.setHeroInfo(game.forcusHero);
					heroTabControl.setTab(0);

					game.addDrawableObject(game.forcusHero);
				}

			}
		});
		equipItemTab.setControl(2, inventoryListBox);

		heroTabControl = new TabControl(2);
		heroTabControl.setControl(0, heroPanel);
		heroTabControl.setControl(1, equipItemTab);

		final Panel heroTab = new Panel(0, 360, 240, buttonH, 4);

		heroTab.setControl(0, new DrawButton(10, 0, 360, buttonW, buttonH));
		heroTab.get(0).setCommand(new ControlCommand() {
			public void Do() {
				if (heroTabControl.getTabIndex() != 0
						&& heroTabControl.visible()) {
					heroTabControl.setTab(0);
				} else {
					heroTabControl.toggleVisible();
					heroTabControl.setTab(0);
					lockScreen = heroTabControl.visible();
				}
			}
		});
		heroTab.setControl(1, new DrawButton(11, 50, 360, buttonW, buttonH));
		heroTab.get(1).setCommand(new ControlCommand() {
			public void Do() {
				heroTabControl.setVisible(false);
				lockScreen = false;
				PlayingCanvas.getGame().extendHandling = new PlaceHeroHandling(
						game.forcusHero);
			}
		});
		heroTab.setControl(2, new DrawButton(7, 200, 360, buttonH, buttonH));
		heroTab.get(2).setCommand(new ControlCommand() {
			public void Do() {
				doneHandling();
			}
		});
		heroTab.setControl(3, heroTabControl);

		// / **************

		toolTab = new TabControl(6);
		toolTab.setControl(0, mainTab);
		toolTab.setControl(1, newHeroTab);
		toolTab.setControl(2, blockTab);
		toolTab.setControl(3, itemTab);
		toolTab.setControl(4, heroTab);
		toolTab.setControl(5, new Panel(0, 360, 240, buttonH, 0));

		mainBar = new Panel(0, 0, 240, 30, 5);
		levelText = new TextControl("Level " + String.valueOf(game.level + 1),
				10, 7);
		lifeText = new TextControl("$(1)" + String.valueOf(game.numLife), 100,
				7);
		moneyText = new TextControl("$(0)" + String.valueOf(game.money), 150, 7);
		mainBar.setControl(0, levelText);
		mainBar.setControl(1, lifeText);
		mainBar.setControl(2, moneyText);
		mainBar.setControl(3, toolTab);
		mainBar.setControl(4, new DrawButton(0, 210, 0, 30, 30));
		mainBar.get(4).setCommand(new ControlCommand() {
			public void Do() {
				stop();
				// pause();
				manualHide = true;
				if(tutorial== null){
					System.out.println("Pause");
					midlet.showPauseCanvas();
				}else{
					System.out.println("Done");
					midlet.showSellectGameCanvas();
				}
			}
		});
	}

	public void initInventory(int type) {
		int k = 0;
		inventoryListBox.clear();
		for (int i = 0; i < game.listItem.size(); i++) {
			ItemEquipment item = (ItemEquipment) game.listItem.elementAt(i);
			if (item.getItemType() == type) {
				tempItem[k] = item;
				inventoryListBox.setInfo(k++, item.getId()
						+ Res.ITEM_ICON_OFFSET);
			}
		}
		itemInfoText.setText("Inventory");
		inventoryListBox.setSellectIndex(-1);
	}

	public void toggleIventory() {

		itemBoxTab.setTab(0);
		// inventoryListBox.setInfo(0,Res.ITEM_ICON_OFFSET);
		for (int i = 0; i < inventoryListBox.getSize(); i++) {
			if (i < game.listItem.size()) {
				inventoryListBox.setInfo(i,
						((ItemEquipment) game.listItem.elementAt(i)).getId()
								+ Res.ITEM_ICON_OFFSET);
			} else {
				inventoryListBox.setInfo(i, -1);
			}

		}
		storeButton.setToggled(false);
		inventoryButton.setToggled(true);
		setIventoryText();
	}

	public void toggleStore() {

		itemBoxTab.setTab(1);
		storeButton.setToggled(true);
		inventoryButton.setToggled(false);
		setStoreText();
	}

	public void setIventoryText() {
		int id = inventoryListBox.getInfo() - Res.ITEM_ICON_OFFSET;
		ItemEquipment item = Factory.createItem(id);
		if (item != null) {
			itemInfoText.setText(item.getInfoText());
		} else {
			itemInfoText.setText("Inventory");
		}
	}

	public void setStoreText() {
		int id = storeListBox.getInfo() - Res.ITEM_ICON_OFFSET;
		ItemEquipment item = Factory.createItem(id);
		if (item != null) {
			itemInfoText.setText(item.getInfoText());
		} else {
			itemInfoText.setText("Store");
		}
	}

	public void initItemBox() {
		itemInfoText = new TextControl("Inventory", 5, 185);

		inventoryListBox = new ListBox(6, 3, 0, 240, 40, 40);
		inventoryListBox.setCommand(new ControlCommand() {
			public void Do() {
				setIventoryText();
			}
		});

		sellButton = new DrawButton(13, 200, 200, 40, 40);
		sellButton.setCommand(new ControlCommand() {
			public void Do() {
				int index = inventoryListBox.getSellectIndex();
				if (index >= 0 && index < game.listItem.size()) {
					int cost = ((ItemEquipment) game.listItem.elementAt(index)).cost / 2;
					game.listItem.removeElementAt(index);
					setMessage("+" + cost);
					game.money += cost;
					toggleIventory();
				}

			}
		});

		storeListBox = new ListBox(6, 3, 0, 240, 40, 40);
		storeListBox.setInfo(new int[] { 21, 22, 23, 24, 25, -1, 26, 27, 28,
				29, 30, -1, 31, 32, 33, 34, 35, -1 });
		storeListBox.setCommand(new ControlCommand() {
			public void Do() {
				setStoreText();
			}
		});
		buyButton = new DrawButton(12, 200, 200, 40, 40);
		buyButton.setCommand(new ControlCommand() {
			public void Do() {
				int id = storeListBox.getInfo() - Res.ITEM_ICON_OFFSET;
				ItemEquipment item = Factory.createItem(id);
				if (item != null) {
					if (game.listItem.size() >= inventoryListBox.getSize()) {
						setMessage("Your inventory box is full");
					} else if (item.cost > game.money) {
						setMessage("Not enough money");
					} else {
						game.listItem.addElement(item);
						game.money -= item.cost;
						setMessage("-" + item.cost + "G");
					}
				}
				storeListBox.setSellectIndex(-1);
				itemInfoText.setText("Store");
			}
		});
	}

	public void endGame(boolean win) {
		stop();
		manualHide = true;
		midlet.showGameOverCanvas(win);
	}

	public boolean isTutorial(){
		return tutorial != null;
	}
	
	public void endRush() {
		toolTab.setTab(0);
		if(game.numLife <= 0){
			return;
		}
		game.extendHandling = new BasicHandling();
		if (tutorial != null) {
			tutorial.endRush();
			return;
		}

		game.level++;
		if (PlayingCanvas.getGame().level == 20) {
			PlayingCanvas.getGame().level = 0;
			endGame(true);
			return;
		}
		
		game.money += 50;
		setMessage("+50");
		
		Enumeration vEnum = game.listHero.elements();
		//System.out.println("wtf");
		while (vEnum.hasMoreElements()) {
			Hero hero = (Hero) vEnum.nextElement();
			if (hero.getHp() <= 0) {
				game.addDrawableObject(hero);
			}
			hero.init();
			hero.idle();
			hero.uplevel();
		}
		//System.out.println("isthatshit");
		saveGame();
	}

	public void lostLife() {
		game.numLife--;
		Res.PlaySound(3);
		if (game.numLife == 0) {
			endGame(false);
		}
	}

	public void saveGame() {
		RecordStore rs = null;
		try {
			// RecordStore.deleteRecordStore("dbx");
			System.out.println("save");
			rs = RecordStore.openRecordStore("dbx", true);

			byte[] data = new byte[6];
			data[0] = -1;
			System.out.println("===>");
			if (rs.getNumRecords() == 0) {
				rs.addRecord(data, 0, 1);
				rs.addRecord(data, 0, 1);
				rs.addRecord(data, 0, 1);
				rs.addRecord(data, 0, 1);
			}
			data[0] = (byte) game.level;
			data[1] = (byte) game.numLife;
			intToByteArray(game.money, 2, data);
			System.out.println("DATA");
			rs.setRecord(1, data, 0, 6);
			for (int i = 0; i < data.length; i++) {
				System.out.println(data[i]);
			}
			int offset = 0;
			int len = game.listItem.size();
			data = new byte[len];
			for (int i = 0; i < game.listItem.size(); i++) {
				data[offset++] = (byte) ((ItemEquipment) game.listItem
						.elementAt(i)).getId();
			}
			System.out.println("ITEM");
			rs.setRecord(2, data, 0, len);

			offset = 0;
			len = game.listFence.size() * 2;
			data = new byte[len];
			for (int i = 0; i < game.listFence.size(); i++) {
				Fence fence = (Fence) game.listFence.elementAt(i);
				data[offset++] = (byte) (fence).getColIndex();
				data[offset++] = (byte) (fence).getRowIndex();
			}
			System.out.println("FENCES");
			rs.setRecord(3, data, 0, len);

			offset = 0;
			len = game.listHero.size() * 20;
			data = new byte[len];
			for (int i = 0; i < game.listHero.size(); i++) {
				Hero hero = (Hero) game.listHero.elementAt(i);
				data[offset++] = (byte) (hero).getColIndex();
				data[offset++] = (byte) (hero).getRowIndex();
				data[offset++] = (byte) (hero).getArmId();
				data[offset++] = (byte) (hero).getSuitId();
				intToByteArray(hero.attack, offset, data);
				offset += 4;
				intToByteArray(hero.defend, offset, data);
				offset += 4;
				intToByteArray(hero.speed, offset, data);
				offset += 4;
				intToByteArray(hero.range, offset, data);
				offset += 4;
			}
			System.out.println("HERO");
			rs.setRecord(4, data, 0, len);

		} catch (RecordStoreFullException e) {
			try {
				RecordStore.deleteRecordStore("dbx");
			} catch (RecordStoreNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (RecordStoreException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} catch (RecordStoreNotFoundException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
			try {
				RecordStore.deleteRecordStore("dbx");
			} catch (RecordStoreNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (RecordStoreException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			try {
				rs.closeRecordStore();
			} catch (Exception e) {
			}
		}
	}

	public void intToByteArray(int value, int o, byte[] output) {
		for (int i = 0; i < 4; i++) {
			int offset = (4 - 1 - i) * 8;
			output[i + o] = (byte) ((value >>> offset) & 0xFF);
		}
	}

	private static int byteArrayToInt(byte[] bytes, int o) {
		int r = 0;
		int b = bytes[o];
		if (b < 0) {
			b += 255;
		}
		r = r | (b << 24);

		b = bytes[o + 1];
		if (b < 0) {
			b += 255;
		}
		r = r | (b << 16);

		b = bytes[o + 2];
		if (b < 0) {
			b += 255;
		}
		r = r | (b << 8);

		b = bytes[o + 3];
		if (b < 0) {
			b += 255;
		}
		r = r | (b);
		return r;
	}

	public boolean existingSavedGame() {
		boolean existingOrNot = false;
		RecordStore rs = null;

		try {
			rs = RecordStore.openRecordStore("dbx", false);
			if (rs.getNumRecords() == 4) {
				rs.closeRecordStore();
				return true;
			}
		} catch (RecordStoreNotFoundException e) {
			existingOrNot = false;
		} catch (Exception e) {
		} finally {
			try {
				rs.closeRecordStore();
			} catch (Exception e) {
			}
		}
		return existingOrNot;
	}

	public void loadGame() {
		tutorial = null;
		RecordStore rs = null;
		try {
			game = new GameManager();
			toolTab.setTab(0);
			rs = RecordStore.openRecordStore("dbx", true);
			byte[] data = rs.getRecord(1);
			game.level = data[0];
			game.numLife = data[1];
			game.money = byteArrayToInt(data, 2);
			
			data = rs.getRecord(2);
			if (data != null) {
				for (int i = 0; i < data.length; i++) {
					game.listItem.addElement(Factory.createItem(data[i]));
				}
			}
			data = rs.getRecord(3);
			if (data != null) {
				for (int i = 0; i < data.length; i += 2) {
					game.AddFence(new Fence(), data[i], data[i + 1]);
				}
			}
			data = rs.getRecord(4);
			if (data != null) {
				for (int i = 0; i < data.length; i += 20) {
					int c = data[i];
					int r = data[i + 1];
					int armId = data[i + 2];
					int suitId = data[i + 3];
					int attack = byteArrayToInt(data, i + 4);
					int defend = byteArrayToInt(data, i + 8);
					int speed = byteArrayToInt(data, i + 12);
					int range = byteArrayToInt(data, i + 16);
					Hero hero = new Hero(attack, defend, speed, range);
					hero.setArm((ItemArm) Factory.createItem(armId));
					hero.setSuit((ItemSuit) Factory.createItem(suitId));
					game.AddHero(hero, c, r);
				}
			}
		} catch (RecordStoreFullException e) {
			e.printStackTrace();
		} catch (RecordStoreNotFoundException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		} finally {
			try {
				rs.closeRecordStore();
			} catch (Exception e) {
			}
		}

	}
	boolean manualHide = false; 
	protected void hideNotify() {
		
		if(manualHide)
		{
			manualHide = false;
			return;
		}
		stop();
		midlet.showPauseCanvas();
		
		//midlet.pauseApp();
	}
}
